#!/bin/bash

# 设置UTF-8编码
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8

# 获取脚本所在目录
cd "$(dirname "$0")"
PROJECT_DIR=$(pwd)

# 终端样式
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
BOLD='\033[1m'

clear
echo ""
echo "================================================"
echo "        建党在线系统 - 快速构建前端"
echo "================================================"
echo ""
echo "${BLUE}[INFO]${NC} 该脚本将构建前端项目"
echo "       1. 管理端 (client)"
echo "       2. 用户端 (front)"
echo ""

# 询问是否继续
read -p "是否继续？(Y/N): " choice
if [[ ! "$choice" =~ ^[Yy]$ ]]; then
    echo "${BLUE}[INFO]${NC} 操作已取消"
    echo ""
    read -n 1 -s -r -p "按任意键退出..."
    exit 0
fi

echo ""
echo "${BLUE}[INFO]${NC} 正在检查Node.js环境..."

if ! command -v node &> /dev/null; then
    echo "${RED}[ERROR]${NC} 未检测到Node.js环境，请先安装Node.js"
    echo ""
    read -n 1 -s -r -p "按任意键退出..."
    exit 1
fi

node_version=$(node -v)
echo "${GREEN}✓${NC} Node.js版本: $node_version"
echo ""

# 构建管理端
echo "================================================"
echo "[1/2] 构建管理端"
echo "================================================"
cd "$PROJECT_DIR/src/main/resources/client"

if [ ! -d "node_modules" ]; then
    echo "${BLUE}[INFO]${NC} 安装管理端依赖..."
    npm install --registry=https://registry.npmmirror.com --legacy-peer-deps
    if [ $? -ne 0 ]; then
        echo "${RED}[ERROR]${NC} 依赖安装失败"
        echo ""
        read -n 1 -s -r -p "按任意键退出..."
        exit 1
    fi
fi

echo "${BLUE}[INFO]${NC} 构建管理端..."
npm run build

if [ $? -eq 0 ]; then
    echo "${GREEN}✓${NC} 管理端构建成功"
else
    echo "${RED}[ERROR]${NC} 管理端构建失败"
    echo ""
    read -n 1 -s -r -p "按任意键退出..."
    exit 1
fi

echo ""

# 构建用户端
echo "================================================"
echo "[2/2] 构建用户端"
echo "================================================"
cd "$PROJECT_DIR/src/main/resources/front"

if [ ! -d "node_modules" ]; then
    echo "${BLUE}[INFO]${NC} 安装用户端依赖..."
    npm install --registry=https://registry.npmmirror.com --legacy-peer-deps
    if [ $? -ne 0 ]; then
        echo "${RED}[ERROR]${NC} 依赖安装失败"
        echo ""
        read -n 1 -s -r -p "按任意键退出..."
        exit 1
    fi
fi

echo "${BLUE}[INFO]${NC} 构建用户端..."
npm run build

if [ $? -eq 0 ]; then
    echo "${GREEN}✓${NC} 用户端构建成功"
else
    echo "${RED}[ERROR]${NC} 用户端构建失败"
    echo ""
    read -n 1 -s -r -p "按任意键退出..."
    exit 1
fi

echo ""
echo "================================================"
echo "           🎉 构建完成！"
echo "================================================"
echo ""
echo "${GREEN}✓${NC} 管理端: $PROJECT_DIR/src/main/resources/client/dist"
echo "${GREEN}✓${NC} 用户端: $PROJECT_DIR/src/main/resources/front/dist"
echo ""
echo "💡 下一步："
echo "   现在可以双击 ${YELLOW}一键启动全部服务.command${NC} 启动系统了"
echo ""
read -n 1 -s -r -p "按任意键退出..."
echo ""

